package com.koron.css2.serviceManage.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.common.web.bean.DepartmentTreeBean;
import com.koron.common.web.mapper.DepartmentMapper;
import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.queryBean.OrgNodeQueryBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.List;

/**
 * 组织架构列表查询
 * @author 59532
 *
 */
public class OrgNodeList implements ServerInterface{
	
	private static Logger logger = LogManager.getLogger(OrgNodeList.class);

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		MessageBean<PageInfo> message = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", PageInfo.class);
		try {
			OrgNodeQueryBean param = JsonUtils.objectToPojo(req.getData(), OrgNodeQueryBean.class);
			if(param.getOrgKind() == null && param.getSeq() == null) {
				message.setCode(Constant.MESSAGE_INT_FAIL);
				message.setDescription("参数不能为空");
				return message;
			}
			List<DepartmentTreeBean> departments = new ArrayList<DepartmentTreeBean>();
			PageHelper.startPage(param.getPage(), param.getPageCount());
			DepartmentMapper mapper = factory.getMapper(DepartmentMapper.class);
			if(param.getOrgKind() != null) {
				departments = mapper.getDepartmentInfoByFlag(param.getOrgKind());
			}else if(param.getSeq() != null) {
				if(param.getSeq() == -1) {
					param.setSeq(2305843009213693952L);
				}
				departments = mapper.getDescendantByParentId(param.getSeq());
			}
			message.setData(new PageInfo<DepartmentTreeBean>(departments));
		} catch (Exception e) {
			logger.error("非法参数", e);
			return MessageBean.create(Constant.ILLEGAL_PARAMETER, "非法参数", void.class);
		}
		return message;
	}
}
